<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model="value"
        shape="round"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @input="isHost"
      />
    </form>
    <div class="search-main">
      <h3>
        <span>实时热搜</span>
        <span><van-icon name="replay" /></span>
      </h3>

      <ul v-if="newHost">
        <li v-for="item in host" :key="item.id" @click="toDetail(item.id)" >
          {{ item.name }}
        </li>
      </ul>
      <ul v-else>
        <li v-for="item in host2" :key="item.id" @click="toDetail(item.id)" >
          {{ item.name }}
        </li>
      </ul>
      <h3>新品</h3>
      <ul>
        <li v-for="item in host" :key="item.id" @click="toDetail(item.id)">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";

import { loadProductsAPI } from "../services/products";
export default {
  data() {
    return {
      value: "",
      host: [],
      host2:[],
      newHost: true,
    };
  },
  created() {
    loadProductsAPI(this.page).then((res) => {
      // console.log(res.data);
      res.data.forEach((item) => {
        this.host.push({ name: item.name, id: item.id });
      });
    });
  },
  methods: {
    onSearch(val) {
      Toast(val);
    },
    onCancel() {
      this.$router.go(-1);
    },
    isHost() {
      if (this.value == "") {
        this.newHost = true;
      } else {
        this.host2=this.host.filter(item=>{
          return item.name.indexOf(this.value.toUpperCase())>-1
        })
        this.newHost = false;
      }
    },
    toDetail(id) {
      this.$router.push({
        name: "Detail",
        params: {
          id,
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.search-main {
  h3 {
    display: flex;
    justify-content: space-between;
  }
  padding: 1rem;
  ul {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 1rem;
  }

  li {
    background-color: #dee1e6;
    padding: 0.4rem;
    margin: 1rem 1rem 0 0;
    border-radius: 2rem;
  }
}
</style>
